define(
	[
		'require'
	],
	function(require){
		function dateCellFormatter(args, column){
			if (args.row.type & $.wijmo.wijgrid.rowType.data) {
				var data = args.row.data,
					dataKey = column.dataKey,
					formatedTime = APM.util.formatDate(data[dataKey], "yyyy-MM-dd H:mm:ss");
				data["_formatted_"+dataKey] = formatedTime;
				args.$container.append(formatedTime);
				return true;
			}
		}  
		var Controller = Ember.Controller.extend({
			/*
				列配置
			*/
			perfColumns: Ember.computed(function(){
				var columns =  [
				{
					headerText: "交易类型名称",
					dataKey:"name",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.name;
							if(data == 0){
								data = 0;
							}else if(!data){
								data = "-";
							}
							var cb = $("<div ></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				},
				{
					headerText: "交易量",
					dataKey:"throughput",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.throughput;
							if(data == 0){
								data = 0;
							}else if(!data){
								data = "-";
							}
							var cb = $("<div></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				},
				{
					headerText: "平均响应时间",
					dataKey:"responseTime",
					_fmtType: "transform_time",
					cellFormatter: APM.util.indicatorCellFormatter
				},
				
				{
					headerText: "成功率",
					dataKey:"successRate",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.successRate;
							if(data == 0){
								data = 0;
							}else if(!data){
								data = "-";
							}
							var cb = $("<div></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				},
				{
					headerText: "错误数",
					dataKey:"error",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.error;
							if(data == 0){
								data = 0;
							}else if(!data){
								data = "-";
							}
							var cb = $("<div></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				}
			];
			if(!this.get("auth.isNormal")){
					columns.push({
						headerText: "操作",
						dataKey:"id",
						width: 130,
						allowSort: false,
						ensurePxWidth: true,
						cellFormatter: function (args, colume) {
							if (args.row.type & $.wijmo.wijgrid.rowType.data) {
								var ctrl = this.get("controller"),
									data = args.row.data,
									$btnGroup = $('<div class="btn-group"></div>').appendTo(args.$container);

								var ub = $('<button class="btn btn-mini" type="button" title="修改关键交易"><i class="icon-edit"/></button>');

								ub.appendTo($btnGroup).on("click",function(){
									ctrl.set("resourceId", data.id);
									var dialog = Broada.getView("set_trade");
									ctrl.requireResourceApdex();
									dialog.openDialog();
								});				

								var ab = $('<button class="btn btn-mini" type="button" title="配置阈值"><i class="icon-cog"/></button>');
					
								ab.appendTo($btnGroup).on("click",function(){
									var configThresholdsView = Broada.getView("businessConfigThresholdView");
									configThresholdsView.set("targetResource", {targetId: ctrl.get("model").id, targetName: data.name});
									configThresholdsView.requireThreshold(ctrl.get("model").id);
									configThresholdsView.openDialog();
								});

								return true;
							}
						}
					});
				}

				return columns;
			}),

			typeValue: '',

			errorcodes: Ember.A(),

			pageSize: 10,

			transactionType: Ember.A(),

			requireResourceApdex: function() {
				var ctrl = this,
					resourceId = this.get("resourceId");
				return this.store.ajax("GET", "resource/"+resourceId+"/apdex_t", {
					resId : resourceId
				})
				.then(function(response){
					var keyTrade = Ember.A(response['result']);
					ctrl.set("tradeName", keyTrade.name);
					ctrl.set("tradeUri", keyTrade.uri);
					ctrl.set("apdex_t", keyTrade.apdex_t);
					return response;
				});
			},
					
			requireData: function(){
				var ctrl = this,
					serviceId = ctrl.get("model.id"),
					typeValue = ctrl.get("typeValue");
				
				var params = {
					"appId": "default",
					"serviceId":serviceId,
					"keyWord": this.get("keyWord"),
				    "startDate": +this.get("startDate"),
					"endDate": +this.get("endDate"),
					"transactionType": typeValue,
					"pageIndex": this.get("pageIndex"),
				    "pageSize": this.get("pageSize"),
				};

				if( isLocalDebugModel ){
					params = undefined;
				}

				return this.store.ajax("GET", "trades/type", params)
				.then(function(response){
					var result = response.result,
						successRate = "business/success/rate",
						responseTime = "business/response_time/avg",
						error = "business/error/count",
						throughput = "business/throughput/total";
						
						result.forEach(function(node){
							if(node.performance[error] == 0){
								node.error = node.performance[error];
							}else if(!node.performance[error]){
								node.error = node.performance[error];
							}
							if(node.performance[responseTime] == 0){
								node.responseTime = node.performance[responseTime];
							}else if(node.performance[responseTime]){
								node.responseTime = node.performance[responseTime];
							}
							if(node.performance[throughput] == 0){
								node.throughput = node.performance[throughput];
							}else if(node.performance[throughput]){
								node.throughput = node.performance[throughput];
							}
							if(node.performance[successRate] == 0){
								node.successRate = 0+"%";
							}else if(!node.performance[successRate]){
								node.successRate = "-";
							}else{
								node.successRate = node.performance[successRate]+"%";
							}
						});

					if (result.length == 0) {
						ctrl.set("pageIndex",0);
						ctrl.set("pageSize",10);
						ctrl.set("totalRows",0);//设置为0显示没有数据
					} else {
						ctrl.set("pageIndex",response.meta.pageIndex);
						ctrl.set("pageSize",response.meta.pageSize);
						ctrl.set("totalRows",response.meta.total);
					}
					ctrl.set("errorcodes",result);
				
					return response;
				});
			},

			actions: {
				search: function() {
					this.set("pageIndex", 0);
					this.requireData();
				},

				pageIndexChanged: function(e, data, view){
					var pageNo = data.newPageIndex;
					this.set("pageIndex", pageNo);
					this.requireData();
				},

				errorGridClicked: function(e, args, view){
					var ctrl = this,
						row = args.cell.row(),
						column = args.cell.column();
					if (row.type & $.wijmo.wijgrid.rowType.data) {
						if(column.dataKey == "uri"){
							ctrl.transitionTo("business.detail.nodedetail.overview");
						}
					}
				},
				scvDownload: function(){
					var ctrl = this,
						serviceId = this.get('model.id'),
						appId = this.get('business.id'),
						menuId = this.get('model.id'),
						startDate = +ctrl.get("startDate"),
						endDate = +ctrl.get("endDate");
						
					confirmDialog("确定要导出交易类型的表格吗？")
					.then(function(){
						var url="/front/rest/apm/trades/downloadTransaction?appId="+appId+"&menuId="+49+"&serviceId="+serviceId+"&name=transactionType&startDate="+startDate+"&endDate="+endDate+"&token="+encodeURIComponent($.cookie("token"));
						window.location.href =url;
					});
				},
				setTrade: function(){
					var ctrl = this;

					var resourceId = this.get("resourceId");
					var name = this.get("tradeName");
					if(!name){
						this.set("formTip", "交易名称不能为空!");
						return;
					}

					var apdex_t = this.get("apdex_t");
					if (apdex_t && !/^[\d]+$|^\d*\.\d+$/.test(apdex_t)) {
						this.set("formTip", "apdex_t值必须为整数或小数！");
						return;
					}

					this.set("formTip", null);
					
					this.store.ajax("PUT", "resource",{
						"resourceId" : resourceId,
						"name" : name,
						"apdex_t" : apdex_t
					}).then(function(response){
						if(response) {
							alertTip("保存成功！", "success");
							ctrl._actions.closeDialog();

							ctrl.requirePerformances();
							
							ctrl.set("tradeName","");
							ctrl.set("tradeUri", "");
							ctrl.set("apdex_t","");
						} else {
							alertTip("保存失败！", "error");
						}
					});
				},

				closeDialog: function(){
					Broada.getView("set_trade").closeDialog();
				},
				timeRangesChange: function(timeRange){
					var ctrl = this,
						locationStart = this.get("locationStart");
					// if(!isSelectedTime){
						ctrl.set("startDate", timeRange.startDate);
						ctrl.set("endDate", timeRange.endDate);
					// }else{
					// 	var view = Broada.getView("businessTimeRangesTopo");
					// 	if(this.get("clickTimePoint") != null){
					// 		this.set("locationStart",true);
					// 		var date = new Date(this.get("clickTimePoint"));
					// 		if(typeof view != "undefined"){
					// 			var range = view.getTimeRange().endDate - view.getTimeRange().startDate;	
					// 			if(range == 60000){
					// 				this.set("startDate", date);
					// 				this.set("endDate", new Date(date.getTime()+range));
					// 			}else{
					// 				this.set("startDate", new Date(date-range));
					// 				this.set("endDate", date);
					// 			}
					// 		}
					// 		typeof view != "undefined"?view.set("btnTxt", date?APM.util.formatDate(date, "f"):null):null;
					// 		this.requireData();
					// 	}
					// };
					
					ctrl.set("pageIndex", 0);
					ctrl.requireData();
				}
			}
		});

		APM.ServiceServerNodeserverTypeController = Controller;
		return Controller;
	}
);